package com.restaurant.validators;

import java.util.ArrayList;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.restaurant.domain.Menuspicy;
import com.restaurant.domain.Spicymaster;
import com.restaurant.service.MenuspicyService;

public class SpicyMasterValidator implements Validator{

	@Autowired
	private MenuspicyService objMenuspicyService;
	
	@Override
	public boolean supports(Class<?> arg0) {
		return Spicymaster.class.isAssignableFrom(arg0);
	}

	@Override
	public void validate(Object arg0, Errors errors) {
		Spicymaster spicymaster = (Spicymaster) arg0;
		
		if(spicymaster.getSpicyname().trim().length()<=0){
			errors.rejectValue("spicyname", "spicy.required");
		}
		
		ArrayList<Menuspicy> listMenuspicies = new ArrayList<Menuspicy>();
		
		try {
			listMenuspicies = (ArrayList<Menuspicy>) objMenuspicyService.loadByHql("from Menuspicy where spicymaster.spicyID = " + spicymaster.getSpicyID());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(listMenuspicies.size()>0){
			errors.rejectValue("alreadyExists", "spicy.exists");
		}
	}

}
